/**
 * Copyright(c)2012 Beijing PeaceMap Co.,Ltd.
 * All right reserved. 
 */
package com.pmc.dwa.security.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Service;

import com.pmc.dwa.common.dao.IGenericDao;
import com.pmc.dwa.common.utils.ConfigParameter;
import com.pmc.dwa.common.utils.PaginationSupport;
import com.pmc.dwa.common.utils.Util;
import com.pmc.dwa.security.model.TRole;
import com.pmc.dwa.security.model.TSect;
import com.pmc.dwa.security.model.TSection;
import com.pmc.dwa.security.model.TSysoperLog;
import com.pmc.dwa.security.model.TUser;
import com.pmc.dwa.security.model.TUserDetails;
import com.pmc.dwa.security.service.IUserService;
import com.pmc.dwa.security.utils.SpringSecurityUtils;

/**
 * @description 
 * @author aokunsang
 * @date 2013-1-6
 */
@Service("userService")
public class UserServiceImpl implements IUserService {
	
	@Resource(name="genericDao")
	private IGenericDao genericDao;
	
	final static String findSectByRolename = "select ts.* from t_sect ts join t_role_sect trs on ts.ID = trs.SECT_ID join t_role tr on trs.ROLE_ID = tr.ID where tr.ROLENAME = ? and ts.PID != '0'";
	final static String findUserDetailsByUserName = "select tc.*,tu.ID as userid,tu.USERNAME,tu.PASSWORD,tu.STATUS as ustatus,tu.TRUENAME as truename from t_section tc right join t_user_section tus on tc.ID = tus.SECTION_ID right join t_user tu on tus.USER_ID = tu.ID where tu.username = ?";
	final static String findUserRolesByUsername = "select tr.* from t_user tu join t_user_role tur on tu.ID = tur.USER_ID join t_role tr on tur.ROLE_ID = tr.ID where USERNAME = ?";
	final static String editUserState = "update t_user set LOGIN_COUNT = LOGIN_COUNT+1,LAST_LOGINIP=?,LAST_LOGINTIME=? where USERNAME = ?";
	final static String editUserPartinfo = "update t_user set TRUENAME=:truename,MOBILENO=:mobileno,UNITTEL=:unittel,HOMETEL=:hometel,EMAIL=:email,ADDR=:addr where ID=:id";
	final static String editUser = "update t_user set PASSWORD=:password,MOBILENO=:mobileno,UNITTEL=:unittel,HOMETEL=:hometel,EMAIL=:email,ADDR=:addr,COMMENTS=:comments where ID=:id";
	final static String findSectionByUid = "select ts.* from t_section ts join t_user_section tus on ts.ID = tus.SECTION_ID join t_user tu on tus.USER_ID = tu.ID where tu.ID = ?";
	final static String addUser = "insert into t_user(ID,USERNAME,PASSWORD,COMMENTS,REG_TIME,USERNO,TRUENAME,MOBILENO,UNITTEL,HOMETEL,EMAIL,ADDR,STATUS,VERSION) values(:username,:password,:comments,:reg_time,:userno,:truename,:mobileno,:unittel,:hometel,:email,:addr,:status,:version)";
	final static String addSyslog = "insert into t_sysoper_log values(:loginUname,:loginUid,:operTime,:operMod,:operEvent,:operFrom,:operPost,:operGet,:operIp,:operRemark)";
	final static String addUserRole = "insert into t_user_role(ROLE_ID,USER_ID,VERSION)values(?,?,?)";
	final static String addUserSection = "insert into t_user_section(SECTION_ID,USER_ID,VERSION,CURR_LOGIN)values(?,?,?,?)";
	
	@Override
	public void addSyslog(HttpServletRequest request, String model,
			String event, String remark) {
		TSysoperLog log = new TSysoperLog();
		TUserDetails userDetails = SpringSecurityUtils.getCurrentUser();
		//当userDetails==null时，获取无效的用户名插入日志表中
		String userName = request.getParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY);
		log.setLoginUid(userDetails!=null ? userDetails.getUserid() : "0");
		log.setLoginUname(userDetails!=null ? userDetails.getUsername() : userName);
		log.setOperIp(Util.getIpAddr(request));
		log.setOperTime(new Date());
		log.setOperMod(model);
		log.setOperEvent(event);
		log.setOperRemark(remark);
		log.setOperFrom(request.getHeader("Referer"));
		@SuppressWarnings("rawtypes")
		Enumeration enum1 = request.getParameterNames();
		String paramdata = "";
		while(enum1.hasMoreElements()){
			String paramName=(String)enum1.nextElement();
			String[] values=request.getParameterValues(paramName);
			for(int i=0;i<values.length;i++){
				if(paramName.toLowerCase().indexOf("password")==-1){
					paramdata += "&" + paramName + "=" + values[i] + "";
				}
			}
		}
		if(request.getMethod().equalsIgnoreCase("POST")){
			log.setOperPost(paramdata);
			log.setOperGet("");
		}else{
			log.setOperPost("");
			log.setOperGet(paramdata);
		}
		genericDao.saveOrUpdate(addSyslog, log);
	}
	@Override
	public List<TRole> findAllRoles() {
		return genericDao.query("select * from t_role", TRole.class);
	}

	@Override
	public List<TSect> findSectByRolename(String rolename) {
		return genericDao.query(findSectByRolename, TSect.class, rolename);
	}

	@Override
	public TUserDetails findUserDetailsByUserName(String username) {
		return genericDao.find(findUserDetailsByUserName, TUserDetails.class, username);
	}
	@Override
	public TSection findValidSection(TSection section) {
		if(section==null || StringUtils.isEmpty(section.getId())){
			return new TSection("0",ConfigParameter.getParamVal("sysconf.properties", "rootname"),"system root",null);
		}
		return section;
	}
	@Override
	public List<TRole> findUserRolesByUsername(String username) {
		return genericDao.query(findUserRolesByUsername, TRole.class, username);
	}

	@Override
	public void editUserState(String username,String ipAddr) {
		genericDao.update(editUserState, ipAddr,new java.util.Date(),username);
	}

	@Override
	public TUser findUserByName(String username) {
		return genericDao.find("select * from t_user where USERNAME = ?", TUser.class, username);
	}

	@Override
	public void editUserPartinfo(TUser user) {
		genericDao.saveOrUpdate(editUserPartinfo, user);
	}

	@Override
	public void editLoginUserPwd(String userid, String newPwd) {
		genericDao.update("update t_user set PASSWORD = ? where ID = ?", newPwd, userid);
	}

	@Override
	public PaginationSupport<TUser> getPagesTUser(String sectionid,String queryname,
			int pageNumber, int pageSize) {
		String queryString = "select t.* from t_user t inner join t_user_section tus on t.ID = tus.USER_ID where 1=1 ";
		if(StringUtils.isNotEmpty(sectionid) && !"0".equals(sectionid)){
			queryString += " and tus.SECTION_ID = '" + sectionid+"'";
		}
		if(StringUtils.isNotEmpty(queryname)){
			queryString += " and t.USERNAME like '%"+queryname+"%'";
		}
		return genericDao.queryListByRows(queryString+"order by tus.SECTION_ID asc,t.REG_TIME desc", TUser.class, pageNumber, pageSize);
	}

	@Override
	public TSection findSectionByUid(String uid) {
		return genericDao.find(findSectionByUid, TSection.class, uid);
	}

	@Override
	public boolean chkDataByCol(String colName, String colVal) {
		long statNumber= genericDao.stat("select count(ID) from t_user t where t."+colName.toUpperCase()+" = ?",colVal);
		return statNumber > 0 ? true :false;
	}

	@Override
	public TUser findUserByid(String userid) {
		return genericDao.find("select * from t_user where ID = ?", TUser.class, userid);
	}

	@Override
	public void editUser(TUser user, String[] sectionid, String[] roleid) {
		genericDao.saveOrUpdate(editUser, user);
		/* 添加用户角色*/
		genericDao.update("delete t_user_role where USER_ID = ?",user.getId());
		List<Object[]> list = new ArrayList<Object[]>();
		for(String rid : roleid){
			list.add(new Object[]{rid,user.getId(),"1.0"});
		}
		genericDao.batchOpeate(addUserRole, list);
//		for(String rid : roleid){
//			genericDao.update("insert into t_user_role(ID,ROLE_ID,USER_ID,VERSION)values(?,?,?,?)",UUID.randomUUID().toString(),rid,user.getId(),"1.0");
//		}
		list.clear();  //清除数据
		/* 添加用户分区*/
		genericDao.update("delete t_user_section where USER_ID = ?",user.getId());
		for(int i=0;i<sectionid.length;i++){
			list.add(new Object[]{sectionid[i],user.getId(),"1.0", i==0 ? "1" : "0"});
		}
		genericDao.batchOpeate(addUserSection, list);
		list = null;
//		for(int i=0;i<sectionid.length;i++){
//			genericDao.update("insert into t_user_section(ID,SECTION_ID,USER_ID,VERSION,CURR_LOGIN)values(?,?,?,?,?)",UUID.randomUUID().toString(),sectionid[i],user.getId(),"1.0", i==0 ? "1" : "0");
//		}
	}

	@Override
	public void addUser(TUser user, String[] sectionid, String[] roleid) {
		genericDao.saveOrUpdate(addUser, user);
		for(String rid : roleid){
			genericDao.update(addUserRole,rid,user.getId(),"1.0");
		}
		/* 添加用户分区*/
		for(int i=0;i<sectionid.length;i++){
			genericDao.update(addUserSection,sectionid[i],user.getId(),"1.0", i==0 ? "1" : "0");
		}
	}

	@Override
	public void editUserColumnVal(String uid, String columnName, String columnVal){
		genericDao.update("update t_user set "+columnName+" = ? where ID = ?" , columnVal, uid);
	}
	@Override
	public void delUser(String uid) {
		genericDao.update("delete from t_user_role where USER_ID = ?", uid);
		genericDao.update("delete from t_user_section where USER_ID = ?", uid);
		genericDao.update("delete from t_user where ID = ?", uid);
	}
}
